// src/stores/auth.ts
import { defineStore } from 'pinia';
import type { ApiResponse } from '@/api/types';
import request from '@/api/request';

// 定义持久化存储的键名
const STORAGE_KEYS = {
  ACCESS_TOKEN: 'auth_access_token',
  REFRESH_TOKEN: 'auth_refresh_token'
};

export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN) || null as string | null,
    refreshToken: localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN) || null as string | null,
    isLoggedIn: !!localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN),
  }),
  persist:{
    key: 'sunlake-auth-store',
    paths: ['accessToken', 'refreshToken', 'isLoggedIn']
  } as any,
  getters: {
    // 获取认证头信息
    authHeader: (state) => {
      if (state.accessToken) {
        return { Authorization: `Bearer ${state.accessToken}` };
      }
      return {};
    }
  },
  
  actions: {
    // 设置令牌并持久化
    setTokens(access: string | null, refresh: string | null) {
      this.accessToken = access;
      this.refreshToken = refresh;
      this.isLoggedIn = !!access;
      
      // 持久化存储
      if (access) {
        localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, access);
      } else {
        localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
      }
      
      if (refresh) {
        localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, refresh);
      } else {
        localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
      }
    },
    
    // 清空令牌
    clearTokens() {
      this.accessToken = null;
      this.refreshToken = null;
      this.isLoggedIn = false;
      localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
      localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
    },
    
    // 刷新令牌
    // async refreshAccessToken(): Promise<string | null> {
    //   if (!this.refreshToken) throw new Error('无刷新令牌');
      
      // try {
      //   const res = await request<ApiResponse<{ accessToken: string }>>({
      //     url: '/auth/refresh',
      //     method: 'POST',
      //     data: { refreshToken: this.refreshToken },
      //     skipAuth: true, // 跳过认证拦截器
      //   });
        
      //   const newToken = res.data.accessToken;
      //   this.setTokens(newToken, this.refreshToken);
      //   return newToken;
      // } catch (error) {
      //   console.error('刷新令牌失败:', error);
      //   this.clearTokens();
      //   return null;
      // }
    // },
    
    // 注销登录
    logout() {
      this.clearTokens();
      // 可以在这里添加跳转登录页等逻辑
    }
  }
});